
const PORT = 8000;
const { Pool } = require('pg');
const pool = new Pool({
  user: 'postgres',
  host: 'project_data_base',
  database: 'project',
  password: '582936',
  port: 5432,
});
const fs = require('fs');
const path = require('path');
class report {
  async reportGet(req, res) {
    try {
      const user_id = req.query.user_id || null; 
      const status_id = req.query.status_id || null; 
      const last_report = req.query.last_report || "";
      const status_sort = req.query.status_sort || "";
      const desc = req.query.desc || false;
      const id = req.query.id || null;
      var i = 1;
      const values = []
      let queryText = `
    SELECT * FROM report 
    WHERE 1=1`; 
      if (req.role === "Scientist") {
        queryText += ` AND user_id = $${i}`;
        i++;
        values.push(req.user.user.id)
      }
      if (id !== null) {
        queryText += ` AND id = $${i}`;
        i++;
        values.push(id)
      }
      else {
        if (user_id !== null) {
          queryText += ` AND user_id = $${i}`;
          i++;
          values.push(user_id)
        }

        if (status_id !== null) {
          queryText += ` AND status_id = $${i}`;
          i++;
          values.push(status_id)
        }

        queryText += `
      ORDER BY`;

        if (status_sort === "") {
          queryText += ` last_report`;
        } else {
          queryText += ` status_id`;
        }
        if (desc == "true"){
          queryText += ` DESC`;
        }
      //   values.push(limit)
      //   values.push(offset)

      //   queryText += `
      // LIMIT $${i} `
      //   i++;
      //   queryText += `OFFSET $${i};`
      //   console.log(queryText)
      }



      const result = await pool.query(queryText, values);
      const reports = result.rows;

      // const nextOffset = reports.length < limit ? 0 : parseInt(offset) + parseInt(limit);
      // const previousOffset = parseInt(offset) - parseInt(limit) >= 0 ? parseInt(offset) - parseInt(limit) : null;

      const response = {
        reports,
        // next: nextOffset === 0 ? null : `http://localhost:${PORT}/api/reports?limit=${limit}&offset=${nextOffset}${(req.query.user_id != null) ? "&user_id=" + user_id : ""}${(req.query.status_id != null) ? "&status_id=" + status_id : ""}${(req.query.status_sort != null) ? "&status_sort=" + status_sort : ""}${(req.query.last_report != null) ? "&last_report=" + last_report : ""}`,
        // previous: previousOffset === null ? null : `http://localhost:${PORT}/api/reports?limit=${limit}&offset=${previousOffset}${(req.query.user_id != null) ? "&user_id=" + user_id : ""}${(req.query.status_id != null) ? "&status_id=" + status_id : ""}${(req.query.status_sort != null) ? "&status_sort=" + status_sort : ""}${(req.query.last_report != null) ? "&last_report=" + last_report : ""}`,
      };

      res.json(response);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  }

  async reportPut(req, res) {
    try {
      const { title, id, file } = req.body;

      const queryText = `
              UPDATE report 
              SET title = $1, 
                  file = $2,
                  status_id = 1,
                  last_report = $4
              WHERE id = $3
              RETURNING *;
            `;
      console.log(req.file)
      const values = [title, req.file.path, id, new Date];

      const result = await pool.query(queryText, values);
      const newreport = result.rows[0];

      res.json(newreport);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  }
  async reportPost(req, res) {
    try {
      const { user_id, title, file } = req.body;

      const filePath = path.join(req.file.path, "")

      const writeStream = fs.createWriteStream(filePath);

      req.on('file', (chunk) => {
        writeStream.write(chunk)
      });

      req.on('end', () => {
        writeStream.end();

        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('File uploaded successfully');
      });

      const queryText = `
              INSERT INTO report (user_id, title, last_report, status_id, file)
              VALUES ($1, $2, $3, 1, $4)
              RETURNING *;
            `;
      const values = [req.user.user.id, title, new Date, filePath];

      const result = await pool.query(queryText, values);
      const newreport = result.rows[0];

      res.json(newreport);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  }
}

module.exports = new report()